import { useState, useEffect } from 'react';
import { Dialog } from 'react-vant';
import './index.less';
import SvgIcon from '../../components/SvgIcon/index';
import { deviceId } from '../../utils/staticData';
import { runningTextConvert } from '../../utils/filters';

export default function Power({ props, onPowerClick, onLoopClick }: any) {
  const { power, isOnline, status } = props;
  const [color, setColor] = useState(power ? 'var(--primary-color)' : '#000');
  const Hejia = (window as any).Hejia;
  useEffect(() => {
    setColor(power ? 'var(--primary-color)' : '#000');
  }, [power]);

  const onSwitchClick = () => {
    if (power === 1) {
      Dialog.confirm({
        message: `设备${runningTextConvert(status)}中，确定要待机吗？`,
        confirmButtonText: '确定',
        confirmButtonColor: 'var(--primary-color)',
        onCancel: () => console.log('cancel'),
        onConfirm: () => {
          onLoopClick(false);
          setColor(
            color === 'var(--primary-color)' ? '#000' : 'var(--primary-color)'
          );
          onPowerClick(power ? 0 : 1);
          Hejia.setControlParam(
            {
              // deviceId,
              parameters: {
                param: [
                  {
                    name: 'Switch',
                    content: 0
                  }
                ]
              }
            },
            function () {
              setTimeout(() => {
                onLoopClick(true);
              }, 2000);
              console.log('success');
            },
            function (msg: string, obj: any) {
              onLoopClick(true);
              console.log(msg + obj.resultCode + obj.resultCodeMessage);
            }
          );
        }
      });
    } else {
      onLoopClick(false);
      setColor(
        color === 'var(--primary-color)' ? '#000' : 'var(--primary-color)'
      );
      onPowerClick(power ? 0 : 1);
      Hejia.setControlParam(
        {
          // deviceId,
          parameters: {
            param: [
              {
                name: 'Switch',
                content: 1
              }
            ]
          }
        },
        function () {
          setTimeout(() => {
            onLoopClick(true);
          }, 2000);
          console.log('success');
        },
        function (msg: string, obj: any) {
          onLoopClick(true);
          console.log(msg + obj.resultCode + obj.resultCodeMessage);
        }
      );
    }
  };
  return (
    <div className="power-mask-wapper">
      {!isOnline && <div className="mask"></div>}
      <div className="power">
        <div className="left">
          <div className="title">开/待机</div>
          <div className="description">{power ? '开机' : '待机'} </div>
        </div>
        <div className="icon" onClick={onSwitchClick}>
          <SvgIcon name="switch" size="48" color={color} />
        </div>
      </div>
    </div>
  );
}
